package service.impl;

import java.util.Map;

import com.opensymphony.xwork2.ActionContext;

import service.interf.ITeacher;

import common.impl.exception.ServiceException;

import net.sf.json.JSONObject;
import dao.interf.ITeacherDao;
import dao.pojo.Classes;
import dao.pojo.Student;
import dao.pojo.Teacher;
import model.MTeacher;
public class TeacherImpl implements ITeacher{
	private ITeacherDao teacherDao;

	public void setTeacherDao(ITeacherDao teacherDao) {
		this.teacherDao = teacherDao;
	}

	@Override
	public String login(MTeacher model) {
		Teacher tea = teacherDao.getByProperty("teaEmail" , model.getTeaEmail());
		Map<String,Object> session = ActionContext.getContext().getSession();
		if (tea == null) {
			return "0";
		} else {
			if (tea.getTeaPassword().equals(model.getTeaPassword())) {
				session.put("teaId", tea.getTeaId());
				session.put("teaName", tea.getTeaName());
				return "1";
			} else {
				return "0";
			}
		}
		
		
	}

	//@Override
	public String register(MTeacher model) {
		Teacher tea = new Teacher();
		tea.setTeaEmail(model.getTeaEmail());
		tea.setTeaName(model.getTeaName());
		tea.setTeaPassword(model.getTeaPassword());
		return teacherDao.add(tea);
	}
	
	@Override
	public String getById(MTeacher model) {
		Teacher tea = teacherDao.getById(model.getTeaId());
		if(null == tea) {
			throw new ServiceException("ERR-0021");
		}
		
		return createTeacherObj(tea).toString();
		
	}
	
	@Override
	public String getInfo() {
		JSONObject obj = new JSONObject();
		Map<String,Object> session = ActionContext.getContext().getSession();
		obj.put("teaId", session.get("teaId"));
		obj.put("teaName", session.get("teaName"));
		return obj.toString();
	}

	@Override
	public String deleteById(Integer id) {
		teacherDao.deleteById(id);
		return "1";
	}

	@Override
	public String edit(MTeacher model) {
		Teacher tea = teacherDao.getById(model.getTeaId());
		if (null == tea) {
			throw new ServiceException("ERR-0021");
		}
		tea.setTeaEmail(model.getTeaEmail());
		tea.setTeaName(model.getTeaName());
		tea.setTeaPassword(model.getTeaPassword());
		
		teacherDao.edit(tea);
		return "1";
	}
	
	private JSONObject createTeacherObj(Teacher tea) {
		JSONObject obj = new JSONObject();
		obj.put("teaId", tea.getTeaId());
		obj.put("teaEmail", tea.getTeaEmail());
		obj.put("teaName", tea.getTeaName());
		return obj;
	}
}
